#include "GTADXGraphic.h"

GTADXGraphic::GTADXGraphic(void)
: m_D3D(NULL), m_Device(NULL), m_Sprite(NULL)
{
	m_BackColor = D3DXCOLOR(0,0,0,1);
}

GTADXGraphic::~GTADXGraphic(void)
{
	Shutdown();	
}

void GTADXGraphic::Shutdown(void)
{
	SAFE_RELEASE(m_Sprite);
	SAFE_RELEASE(m_Device);
	SAFE_RELEASE(m_D3D);
}

bool GTADXGraphic::Create(HWND hWnd, int width , int height)
{
	m_D3D = Direct3DCreate9(D3D_SDK_VERSION);
	if (NULL == m_D3D)
	{
		return false;
	}

	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));

	d3dpp.BackBufferWidth = width;
	d3dpp.BackBufferHeight = height;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.hDeviceWindow = hWnd;
	d3dpp.Windowed = TRUE;

	HRESULT hr = m_D3D->CreateDevice(
		0,
		D3DDEVTYPE_HAL,
		hWnd,
		D3DCREATE_HARDWARE_VERTEXPROCESSING, // D3DCREATE_SOFTWARE_VERTEXPROCESSING
		&d3dpp,
		&m_Device);

	if (FAILED(hr))		// SUCCEEDED(hr)
	{
		// 
		return false;
	}

	hr = D3DXCreateSprite(m_Device, &m_Sprite);
	if (FAILED(hr))
	{
		return false;
	}

	return true;
}

void GTADXGraphic::SetBackColor(BYTE r, BYTE g, BYTE b)
{
	m_BackColor = D3DXCOLOR(D3DCOLOR_XRGB(r, g, b));
}

void GTADXGraphic::BeginRender (void)
{
	m_Device->Clear(0, NULL, D3DCLEAR_TARGET, m_BackColor, 1.0f, 0);
	m_Device->BeginScene();

	m_Sprite->Begin(D3DXSPRITE_ALPHABLEND/* | D3DXSPRITE_SORT_TEXTURE*/);
}

void GTADXGraphic::EndRender (void)
{
	m_Sprite->End();
	m_Device->EndScene();
	m_Device->Present(NULL, NULL, NULL, NULL);
}

void GTADXGraphic::Draw(LPDIRECT3DTEXTURE9 pTexture)
{
	m_Sprite->Draw(
		pTexture, 
		NULL, 
		NULL,
		NULL,
		D3DXCOLOR(1.0f, 1.0f, 1.0f, 0.5f)
		);
}

void GTADXGraphic::Draw(LPDIRECT3DTEXTURE9 pTexture, int dx, int dy, int width, int height, int sx, int sy)
{	
	RECT r;
	SetRect(&r, sx, sy, sx + width, sy + height);

	D3DXVECTOR3 p ((float)dx, (float)dy, 0);

	m_Sprite->Draw(
		pTexture, 
		&r, 
		NULL,
		&p,
		D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f)
		);
}
